package com.guli.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.base.exception.GuliException;
import com.guli.edu.entity.Course;
import com.guli.edu.entity.CourseDescription;
import com.guli.edu.entity.form.CourseForm;
import com.guli.edu.entity.fuzzy.CourseLike;
import com.guli.edu.entity.fuzzy.CourseLikeFront;
import com.guli.edu.entity.vo.CoursePublishVo;
import com.guli.edu.entity.vo.CourseWebVo;
import com.guli.edu.mapper.CourseMapper;
import com.guli.edu.service.CourseDescriptionService;
import com.guli.edu.service.CourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author ZhaoZhenyu
 * @since 2022-09-26
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    // 将课程简介加入description表中去
    @Autowired
    private CourseDescriptionService descriptionService;

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public String saveCourse(CourseForm courseForm) {
        Course course = new Course();
        course.setStatus(Course.COURSE_DRAFT);
        BeanUtils.copyProperties(courseForm, course);
        boolean flag1 = this.save(course);
        if (!flag1) throw new GuliException(20001, "课程信息保存失败");
        // 将简介放入简介表中
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseForm.getDescription());
        // 课程简介表id 与 课程表id 一致
        String cid = course.getId();
        courseDescription.setId(cid);
        boolean flag2 = descriptionService.save(courseDescription);
        if(!flag2) throw new GuliException(20001, "课程简介信息保存失败");
        return cid;
    }

    @Override
    public void getCourseByLikePage(Page<Course> pageParam, Integer size, CourseLike courseLike) {
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("gmt_create");
        if (ObjectUtils.isEmpty(courseLike)){
            baseMapper.selectPage(pageParam, wrapper);
            return;
        }
        String title = courseLike.getTitle();
        String subjectId = courseLike.getSubjectId();
        String subjectParentId = courseLike.getSubjectParentId();
        String teacherId = courseLike.getTeacherId();
        if (StringUtils.hasText(title)) wrapper.eq("title", title);
        if (StringUtils.hasText(subjectId)) wrapper.eq("subject_id", subjectId);
        if (StringUtils.hasText(subjectParentId)) wrapper.eq("subject_parent_id", subjectParentId);
        if (StringUtils.hasText(teacherId)) wrapper.eq("teacher_id", teacherId);
        baseMapper.selectPage(pageParam, wrapper);
    }

    @Override
    public CourseForm getCourseFormById(String id) {
        Course course = this.getById(id);
        if (course == null) throw new GuliException(20001, "课程不存在");
        CourseForm courseForm = new CourseForm();
        BeanUtils.copyProperties(course,courseForm);
        CourseDescription courseDescription = descriptionService.getById(id);
        courseForm.setDescription(courseDescription.getDescription());
        return courseForm;
    }

    @Override
    public boolean updateCourseFormById(String id, CourseForm courseForm) {
        try {
            Course course = new Course();
            BeanUtils.copyProperties(courseForm, course);
            boolean flag1 = this.updateById(course);
            if (!flag1) throw new GuliException(20001, "课程信息保存失败");
            // 将简介放入简介表中
            CourseDescription courseDescription = new CourseDescription();
            courseDescription.setDescription(courseForm.getDescription());
            // 课程简介表id 与 课程表id 一致
            String cid = course.getId();
            courseDescription.setId(cid);
            boolean flag2 = descriptionService.updateById(courseDescription);
            if(!flag2) throw new GuliException(20001, "课程简介信息保存失败");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 课程发布数据回显
    @Override
    public CoursePublishVo getCoursePublishVoById(String id) {
        return courseMapper.selectCoursePublishVoById(id);
    }

    // 课程发布 改字段status
    @Override
    public void publishCourseById(String id) {
        Course course = new Course();
        course.setId(id);
        course.setStatus(Course.COURSE_NORMAL);
        int count = baseMapper.updateById(course);
        if (count == 0) throw new GuliException(20001, "发布课程失败");
    }

    // 添加redis缓存
    @Cacheable(value = "course",key = "'getHotCourse'")
    @Override
    public List<Course> getHotCourse() {
        QueryWrapper<Course> courseWrapper = new QueryWrapper<>();
        courseWrapper.orderByDesc("id").last("limit 8");
        return baseMapper.selectList(courseWrapper);
    }

    @Override
    public Map<String, Object> getCourseByPageLikeOfFront(Page<Course> pageParam, CourseLikeFront courseLikeFront) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(courseLikeFront.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseLikeFront.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseLikeFront.getSubjectId())) {
            queryWrapper.eq("subject_id", courseLikeFront.getSubjectId());
        }

        if (!StringUtils.isEmpty(courseLikeFront.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseLikeFront.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseLikeFront.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam, queryWrapper);

        List<Course> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Override
    public CourseWebVo getInfoWebById(String courseId) {
        return courseMapper.selectInfoWebById(courseId);
    }

    // 每次观看viewCount+1
    @Override
    public void updatePageViewCount(String id) {
        Course course = baseMapper.selectById(id);
        // TODO 更新一条信息最好是单独sql语句 一起更新浪费数据库资源
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
    }


}
